package com.macro.mall.controller;

import com.macro.mall.dto.UmsAdminLogParam;
import com.macro.mall.dto.UmsAdminParam;
import com.macro.mall.dto.UpdateAdminPasswordParam;
import com.macro.mall.service.UmsAdminService;
import com.macro.mall.service.UmsRoleService;
import com.macro.model.UmsAdmin;
import com.macro.model.UmsPermission;
import com.macro.model.UmsRole;
import common.api.CommonPage;
import common.api.CommonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@Api(tags = "UmsAdminController", description = "后台用户管理")
@RequestMapping("/admin")
public class UmsAdminController {

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("{jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private UmsAdminService umsAdminService;
    @Autowired
    private UmsRoleService umsRoleService;

    @ApiOperation("用户注册")
    @PostMapping("/reg")
    @ResponseBody
    public CommonResult register(@RequestBody UmsAdminParam adminParam, BindingResult result){
        UmsAdmin user = umsAdminService.register(adminParam);
        if(user == null)
            return CommonResult.failed();
        return CommonResult.success(user);
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    @ResponseBody
    public CommonResult login(@RequestBody UmsAdminLogParam logParam,BindingResult result){
        String token = umsAdminService.login(logParam.getUsername(),logParam.getPassword());
        if (token == null)
            return CommonResult.validateFailed("用户名或密码错误");

        Map<String,String> tokenMap = new HashMap<>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHead",tokenHead);
        return CommonResult.success(tokenMap);
    }

    @ApiOperation("刷新Token")
    @GetMapping("/refreshToken")
    @ResponseBody
    public CommonResult refreshToken(HttpServletRequest request){
        String token = request.getParameter(tokenHeader);
        String refreshToken = umsAdminService.refreshToken(token);
        if(refreshToken == null)
            return CommonResult.failed("Token已经过期");

        Map<String,String> tokenMap = new HashMap<>();
        tokenMap.put("token",refreshToken);
        tokenMap.put("tokenHead",tokenHead);
        return CommonResult.success(tokenMap);
    }


    @ApiOperation("获取当前用户信息")
    @GetMapping("/info")
    @ResponseBody
    public CommonResult getAdminInfo(Principal principal){
        // 会从 SecurityContext里取出已经认证的用户
        if (principal == null){
            return CommonResult.unauthorized(null);
        }
        String userName = principal.getName();
        UmsAdmin user = umsAdminService.getUmsAdminByName(userName);
        List<String> roles = umsAdminService.getRoleList(user.getId()).stream().map(UmsRole::getName).collect(Collectors.toList());
        Map<String, Object> data = new HashMap<>();
        data.put("username",userName);
        data.put("roles",roles);
        data.put("menus",umsRoleService.getMenuList(user.getId()));
        data.put("icon",user.getIcon());

        return CommonResult.success(data);
    }


    @ApiOperation("获取指定用户信息")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<UmsAdmin> getItem(@PathVariable Long id) {
        UmsAdmin admin = umsAdminService.getItemById(id);
        return CommonResult.success(admin);
    }



    @ApiOperation(value = "登出功能")
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult logout() {
        return CommonResult.success(null);
    }


    @ApiOperation("根据用户名或姓名分页获取用户列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<CommonPage<UmsAdmin>> list(@RequestParam(value = "keyword", required = false) String keyword,
                                                   @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                                   @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        List<UmsAdmin> adminList = umsAdminService.list(keyword, pageSize, pageNum);
        return CommonResult.success(CommonPage.restPage(adminList));
    }

    @ApiOperation("更新密码")
    @PostMapping("/updatePassword")
    @ResponseBody
    public CommonResult updatePassword(@RequestBody UpdateAdminPasswordParam updatePasswordParam){
        int flag = umsAdminService.updatePassword(updatePasswordParam);
        switch (flag){
            case 1:
                return CommonResult.success(flag);
            case -1:
                return CommonResult.failed("参数不合法");
            case -2:
                return CommonResult.failed("无法找到该用户");
            case -3:
                return CommonResult.failed("密码错误");
            default:
                return CommonResult.failed();
        }
    }

    @ApiOperation("删除指定用户信息")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult delete(@PathVariable Long id) {
        int count = umsAdminService.delete(id);

        return count > 0 ? CommonResult.success(count) : CommonResult.failed();
    }


    @ApiOperation("修改帐号状态")
    @RequestMapping(value = "/updateStatus/{id}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateStatus(@PathVariable Long id,@RequestParam(value = "status") Integer status) {
        UmsAdmin umsAdmin = new UmsAdmin();
        umsAdmin.setStatus(status);
        int count = umsAdminService.update(id,umsAdmin);

        return count > 0 ? CommonResult.success(count) : CommonResult.failed();
    }


    @ApiOperation("给用户分配角色")
    @RequestMapping(value = "/role/update", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateRole(@RequestParam("adminId") Long adminId,
                                   @RequestParam("roleIds") List<Long> roleIds) {
        int count = umsAdminService.updateRole(adminId, roleIds);

        return count > 0 ? CommonResult.success(count) : CommonResult.failed();
    }


    @ApiOperation("获取指定用户的角色")
    @RequestMapping(value = "/role/{adminId}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<UmsRole>> getRoleList(@PathVariable Long adminId) {
        List<UmsRole> roleList = umsAdminService.getRoleList(adminId);
        return CommonResult.success(roleList);
    }


    @ApiOperation("给用户分配+-权限")
    @RequestMapping(value = "/permission/update", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updatePermission(@RequestParam Long adminId,
                                         @RequestParam("permissionIds") List<Long> permissionIds) {
        int count = umsAdminService.updatePermission(adminId, permissionIds);

        return count > 0 ? CommonResult.success(count) : CommonResult.failed();
    }

    @ApiOperation("获取用户所有权限（包括+-权限）")
    @RequestMapping(value = "/permission/{adminId}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<UmsPermission>> getPermissionList(@PathVariable Long adminId) {
        List<UmsPermission> permissionList = umsAdminService.getPermissionList(adminId);
        return CommonResult.success(permissionList);
    }

}
